using System;
using System.Collections.Generic;
using System.Linq;
using UMC.Data;
using UMC.ITME.Entities;
using UMC.Net;
using UMC.Web;
using UMC.Web.UI;

namespace UMC.ITME.Activities
{
    [UMC.Web.Apiumc("ITME", "UI", Auth = WebAuthType.User)]
    public class SiteUIActivity : UMC.Web.WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var webr = UMC.Data.WebResource.Instance();
            var ui = UISection.Create(new UITitle("我的应用"));

            // var list = new List<WebMeta>();
            if (request.IsApp)
            {
                ui.Title.Banner("ITME", "System", "Search", "Hot");
                ui.Title.Name("icon", "\uea0e");
            }

            var cfg = UMC.Data.Reflection.Configuration("BgSrc");
            var bgsrcs = new List<WebMeta>();
            var now = DateTime.Now;
            foreach (var b in cfg.Providers)
            {
                int satrt = Utility.IntParse(b["start"], 0) % 24;
                int end = Utility.IntParse(b["end"], 0) % 24;
                if (satrt <= now.Hour && end >= now.Hour)
                {
                    var time = b["time"];
                    bgsrcs.Add(new WebMeta().Put("src", webr.ImageResolve(request.Url, b.Name, "1", 0, $"umc-image=m350x200&{time}")));
                }
            }
            if (bgsrcs.Count == 0)
            {
                bgsrcs.Add(new WebMeta().Put("src", new Uri(request.Url, $"/css/images/BgSrc/bg5.jpg?umc-image=m350x200").AbsoluteUri));

            }

            ui.Title.Right(new UIEventText().Icon('\ue94d').Click(new UIClick(request.Model, "Customer")));

            ui.UIHeader = new UIHeader().Slider(bgsrcs.ToArray());//new WebMeta[] { new WebMeta().Put("src", surl) });
            UMC.Web.UI.UIIcon iIcon = new Web.UI.UIIcon();
            var user = this.Context.Token.Identity();
            if (request.IsMaster)
            {
                iIcon.Add(new UIEventText("我的设备").Src(new Uri(request.Url, "/css/images/icon/computer.png").AbsoluteUri).Click(new UIClick("ITME", "SSH")));
                iIcon.Add(new UIEventText("应用管理").Src(new Uri(request.Url, "/css/images/icon/appmgr.png").AbsoluteUri).Click(new UIClick("ITME", "Site")));
                iIcon.Add(new UIEventText("组织账户").Icon('\uf0c0', 0x36a3f7).Click(new UIClick("Settings", "Organize")));
                iIcon.Add(new UIEventText("功能授权").Icon('\uf214', 0xf4516c).Click(new UIClick("Settings", "AuthKey")));
                ui.Add(iIcon);


            }

            var home = WebServlet.MainDomain;

            var sites = DataFactory.Instance().Site().Where(r => r.Flag != -1).Where(r => (r.IsModule ?? false) == false)
            .OrderBy(r => r.Seq ?? 1000).ToList();

            var keys = new Set<StringValue>((x, y) => x.Span.SequenceCompareTo(y.Span));
            var groupKeys = new Set<StringValue>((x, y) => x.Span.SequenceCompareTo(y.Span));
            groupKeys.Put(new StringValue("Site/Group/0"));

            Utility.Each(sites, r =>
           {
               keys.Put(new StringValue($"Desktop/{r.Root}"));
               groupKeys.Put(new StringValue($"Site/Group/{r.GroupKey ?? 0}"));
           });


            var auths = UMC.Security.AuthManager.IsAuthorization(user, 0, keys.Span.ToArray());

            // var groupKeys = groupKes.ToArray();

            var groupAuths = UMC.Security.AuthManager.IsAuthorization(user, 0, groupKeys.Span.ToArray());

            var ds = new List<Site>();
            var union = WebServlet.DomainUnion;
            for (var i = 0; i < sites.Count; i++)
            {
                var d = sites[i];

                if (auths[i].Item1)
                {
                    switch (d.AuthType ?? Web.WebAuthType.User)
                    {
                        case Web.WebAuthType.Admin:
                            if (user.IsInRole(UMC.Security.Membership.AdminRole))
                            {
                                ds.Add(d);
                            }
                            else if (UMC.Data.DataFactory.Instance().Roles(user.Id.Value, d.SiteKey.Value).Contains(UMC.Security.Membership.AdminRole))
                            {
                                ds.Add(d);
                            }
                            break;
                        default:
                            ds.Add(d);
                            break;
                    }
                }
            }

            var siteGroups = DataFactory.Instance().SiteGroup().OrderBy(r => r.Seq ?? 0).ToList();
            if (request.IsMaster)
            {
                siteGroups.Insert(0, new SiteGroup { Key = 0, Caption = "我的应用" });
            }
            else
            {
                siteGroups.Insert(0, new SiteGroup { Key = 0 });
            }

            foreach (var sg in siteGroups)
            {
                var l = ds.FindAll(r => (r.GroupKey ?? 0) == sg.Key);
                if (l.Count > 0)
                {
                    if (groupAuths[groupKeys.IndexOf(new StringValue($"Site/Group/{sg.Key}"))].Item1)
                    {
                        var appUI = ui.NewSection();
                        appUI.Header.Put("text", sg.Caption);

                        var appIcons = new Web.UI.UIIcon();

                        appIcons.Style.AlignLeft();
                        appUI.Add(appIcons);
                        foreach (var d in l)
                        {
                            var strUrl = $"{request.Url.Scheme}://{d.Root}{union}{home}/UMC.For/{request.Server}";

                            var title = d.Caption ?? ""; ;

                            if ((d.OpenModel ?? 0) == 3)
                            {
                                strUrl = new Uri(new Uri(SiteConfig.Config(d.Domain)[0]), d.Home ?? "/").AbsoluteUri;
                            }
                            else if (SiteConfig.Config(d.AuthConf).Contains("*") || d.AuthType == WebAuthType.All)
                            {
                                strUrl = $"{request.Url.Scheme}://{d.Root}{union}{home}{d.Home}";

                            }
                            if (String.IsNullOrEmpty(d.MobileHome))
                            {
                                appIcons.Add(new UIEventText(title.Trim()).Click(UIClick.Url(strUrl)).Src(webr.ImageResolve(request.Url, d.Root, "1", 4, $"_t={d.ModifyTime}")));
                            }
                            else
                            {
                                if (d.MobileHome.StartsWith("/UMC/"))
                                {
                                    appIcons.Add(new UIEventText(title.Trim()).Click(Utility.Scanning(d.MobileHome) ?? UIClick.Url(strUrl)).Src(webr.ImageResolve(request.Url, d.Root, "1", 4, $"_t={d.ModifyTime}")));
                                }
                                else
                                {
                                    strUrl = $"{request.Url.Scheme}://{d.Root}{union}{home}{d.MobileHome}";
                                    appIcons.Add(new UIEventText(title.Trim()).Click(UIClick.Url(strUrl)).Src(webr.ImageResolve(request.Url, d.Root, "1", 4, $"_t={d.ModifyTime}")));
                                }
                            }
                        }

                    }
                }

            }
            if (ds.Count == 0)
            {

                UIDesc desc = new UIDesc("应用为空");
                desc.Desc("{icon}\n{desc}").Put("icon", "\uf24a");
                desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));
                ui.NewSection().Add(desc);

            }
            if (request.IsMaster == false && request.IsCashier)
            {
                var searcher = UMC.Data.HotCache.Search<Entities.Device>();

                var devices = searcher.Query(new Entities.Device(), false, 0, 1500, out var index);

                var ds3 = devices.Select(r => new StringValue($"Device/{r.Id}")).ToArray();
                var auths4 = UMC.Security.AuthManager.Authorization(user, 0, ds3);


                iIcon.Style.AlignLeft();
                int i = 0;
                foreach (var d in devices)
                {
                    if (auths4[i].Item1 > 0)
                    {
                        iIcon.Add(new UIEventText(d.Caption).Icon('\uf17c', 0x111).Click(new UIClick("ITME", "SSH", d.Id.ToString())));
                    }
                    i++;
                }
                if (iIcon.Count > 0)
                    ui.NewSection().Add(iIcon).Header.Put("text", "我的设备");

            }

            ui.SendTo(this.Context, $"{request.Model}.{request.Command}");

        }

    }
}